package com.zhidisoft.admin.controller;

import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.zhidisoft.admin.entity.User;
import com.zhidisoft.admin.service.IUserService;
import com.zhidisoft.admin.vo.AjaxVo;
import com.zhidisoft.admin.vo.UserVo;

@Controller	//类似Struts的Action
public class LoginController {
	
	@Autowired
	private IUserService service;
	/**
	 * 进入登陆界面
	 * @return
	 */
	@GetMapping("/login")
  //@RequestMapping(value="/login",method=RequestMethod.GET) 同@GetMapping注解一个意思
	public ModelAndView login(String servletPath) {
		return new ModelAndView("login.html","servletPath",servletPath);
	}
	
	/**
	 *2,登陆按钮
	 * @return
	 */
	@PostMapping("/login")
	@ResponseBody	//看到responseBody,就要想到返回值类型为Ajax;
	public AjaxVo login(UserVo userVo,HttpSession session){
		if (userVo == null) 
			return new AjaxVo().setErrorCode("1001").setErrorMsg("用户名或密码不能为空！");
		if (StringUtils.isEmpty(userVo.getUsername())||StringUtils.isEmpty(userVo.getPassword())) 
			return new AjaxVo().setErrorCode("1001").setErrorMsg("用户名或密码不能为空！");
		User dbUser = service.findByUserName(userVo.getUsername());
		if (dbUser == null) 
			return new AjaxVo().setErrorCode("1002").setErrorMsg("用户名不存在！");
		if (!userVo.getPassword().equals(dbUser.getPassword())) 
			return new AjaxVo().setErrorCode("1002").setErrorMsg("密码输入有误！");
		session.setAttribute("userId", dbUser.getId());
		return new AjaxVo().setErrorCode("0");
	}
}
